<template>
  <view class="shop-container">
    <!-- 左侧分类导航 -->
    <view class="category-sidebar">
      <view class="category-header">
        <text class="category-title">分类</text>
      </view>
      <scroll-view scroll-y class="category-scroll">
        <!-- 全部分类 -->
          <view 
            class="category-item" 
            :class="{active: currentCategoryId === 'all'}"
            :style="currentCategoryId === 'all' ? 'background-color: ' + primaryColor + '20' : ''"
            @click="selectCategory('all', '全部')">
            <text class="category-text" :style="currentCategoryId === 'all' ? 'color: ' + primaryColor : ''">全部</text>
          </view>
        
        <!-- 父级分类 -->
        <view v-for="parentCategory in categories" :key="parentCategory.categoryId">
          <view 
            class="category-item parent-category" 
            :class="{active: currentCategoryId === parentCategory.categoryId, expanded: parentCategory.expanded}"
            :style="currentCategoryId === parentCategory.categoryId ? 'background-color: ' + primaryColor + '20' : ''"
          >
            <view class="category-content" @click="selectCategory(parentCategory.categoryId, parentCategory.categoryName)">
              <text class="category-text" :style="currentCategoryId === parentCategory.categoryId ? 'color: ' + primaryColor : ''">{{ parentCategory.categoryName }}</text>
            </view>
            <text class="expand-icon" v-if="parentCategory.children && parentCategory.children.length > 0"
                  @click.stop="toggleParentCategory(parentCategory)">
              {{ parentCategory.expanded ? '▼' : '▶' }}
            </text>
          </view>
          
          <!-- 子级分类 -->
          <view v-if="parentCategory.expanded && parentCategory.children" class="child-categories">
            <view 
              v-for="childCategory in parentCategory.children" 
              :key="childCategory.categoryId"
              class="category-item child-category" 
              :class="{active: currentCategoryId === childCategory.categoryId}"
              :style="currentCategoryId === childCategory.categoryId ? 'background-color: ' + primaryColor + '20' : ''"
              @click="selectCategory(childCategory.categoryId, childCategory.categoryName)"
            >
              <text class="category-text" :style="currentCategoryId === childCategory.categoryId ? 'color: ' + primaryColor : ''">{{ childCategory.categoryName }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 右侧商品列表 -->
    <view class="product-content">
      <scroll-view scroll-y class="product-scroll" @scrolltolower="loadMore">
        <!-- 商品网格 -->
        <view class="product-grid">
          <view 
            class="product-card"
            v-for="(product, index) in currentProducts" 
            :key="index"
            @click="viewProduct(product)"
          >
            <view class="product-image-container">
              <image class="product-image" :src="product.image" mode="aspectFit"></image>
              <view class="product-badge" v-if="product.isHot" :style="{background: 'linear-gradient(135deg, ' + primaryColor + ', ' + primaryColor + 'CC)', boxShadow: '0 2px 8px ' + primaryColor + '40'}">
                <text class="badge-text">热销</text>
              </view>
            </view>
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <view class="product-price-row">
                <text class="product-price" :style="{color: primaryColor}">¥{{ product.price }}</text>
                <text class="product-original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
              </view>
              <view class="product-bottom">
                <text class="product-sales">已售{{ product.sales }}件</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 空状态提示 -->
        <view class="empty-state" v-if="!isLoading && currentProducts.length === 0">
          <image class="empty-image" src="/static/images/empty-product.svg" mode="aspectFit"></image>
          <text class="empty-text">该分类还没有商品</text>
          <text class="empty-desc">敬请期待更多精彩商品</text>
        </view>
        
        <!-- 加载更多提示 -->
        <view class="loading-more" v-if="isLoading">
          <text class="loading-text" :style="{color: primaryColor}">加载中...</text>
        </view>
        <view class="no-more" v-if="!hasMore && currentProducts.length > 0">
          <text class="no-more-text" :style="{color: primaryColor}">已经到底了~</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 底部安全区域，避免内容被TabBar遮挡 -->
    <view class="tabbar-safe-area"></view>
    
    <!-- 自定义TabBar -->
    <CustomTabbar :currentPath="'pages/shop/index'" />
  </view>
</template>

<script>
import { listMobileProduct, listMobileProductByCategory } from '@/api/product'
import { listMobileCategoryTree } from '@/api/category'
import { API_CONFIG } from '@/api/config.js'
import { getThemePrimaryColor, getThemeColorFromGlobal } from '@/utils/theme.js'

export default {
  data() {
    return {
      currentCategoryId: 'all',
      currentCategoryName: '全部',
      isLoading: false,
      hasMore: true,
      currentPage: 1,
      pageSize: 10, // 改为10个一页，支持分页加载
      
      categories: [], // 树形分类数据
      allProducts: [], // 当前分类的商品数据
      selectedCategoryIds: [], // 当前选中分类及其子分类的ID列表
      themeColor: '1' // 主题色标识
    }
  },
  computed: {
    currentProducts() {
      // 直接返回当前加载的商品数据，因为已经按分类过滤了
      return this.allProducts
    },
    
    // 主色调
    primaryColor() {
      return getThemePrimaryColor(this.themeColor)
    },
    

  },
  async onLoad(options) {
    // 接收从首页传递的类别参数
    if (options.category) {
      this.currentCategoryId = options.category
    }
    // 初始化主题色
    await this.initThemeColor()
    // 加载数据
    this.loadCategories().then(() => {
      // 分类加载完成后再加载商品
      this.loadProducts()
    })
  },
  
  async onShow() {
    // 页面显示时同步主题色
    await this.initThemeColor()
  },

  methods: {
    // 选择分类
    selectCategory(categoryId, categoryName) {
      this.currentCategoryId = categoryId
      this.currentCategoryName = categoryName
      this.currentPage = 1
      this.hasMore = true
      this.allProducts = []
      
      // 获取当前分类及其子分类的ID列表
      this.selectedCategoryIds = this.getCategoryIds(categoryId)
      
      // 重新加载商品
      this.loadProducts()
    },
    
    // 切换父级分类的展开/收起状态
    toggleParentCategory(parentCategory) {
      // 如果有子分类，则切换展开状态
      if (parentCategory.children && parentCategory.children.length > 0) {
        this.$set(parentCategory, 'expanded', !parentCategory.expanded)
      } else {
        // 如果没有子分类，直接选择该分类
        this.selectCategory(parentCategory.categoryId, parentCategory.categoryName)
      }
    },
    
    // 获取分类及其子分类的ID列表
    getCategoryIds(categoryId) {
      if (categoryId === 'all') {
        return []
      }
      
      const ids = [categoryId]
      
      // 查找该分类的所有子分类
      const findChildren = (categories, targetId) => {
        for (const category of categories) {
          if (category.categoryId === targetId && category.children) {
            for (const child of category.children) {
              ids.push(child.categoryId)
              findChildren([child], child.categoryId)
            }
          }
          if (category.children) {
            findChildren(category.children, targetId)
          }
        }
      }
      
      findChildren(this.categories, categoryId)
      return ids
    },
    
    viewProduct(product) {
      // 提取原始商品ID，去除_dup_后缀
      const originalId = this.getOriginalProductId(product.id)
      uni.navigateTo({
        url: `/pages/product/detail?id=${originalId}`
      })
    },
    
    // 获取原始商品ID，去除_dup_后缀
    getOriginalProductId(id) {
      if (!id) return 1
      // 如果ID包含_dup_，提取原始ID
      if (typeof id === 'string' && id.includes('_dup_')) {
        return id.split('_dup_')[0]
      }
      return id
    },

    loadMore() {
      if (this.hasMore && !this.isLoading) {
        // 加载更多商品数据
        this.loadProducts(true)
      } else {
        // 跳过loadMore：正在加载中或没有更多数据
      }
    },
    
    // 检查缓存是否有效（10分钟有效期）
    isCacheValid(cacheKey) {
      const cacheData = uni.getStorageSync(cacheKey)
      if (!cacheData || !cacheData.timestamp) {
        return false
      }
      const now = Date.now()
      const cacheTime = cacheData.timestamp
      const tenMinutes = 10 * 60 * 1000 // 10分钟的毫秒数
      return (now - cacheTime) < tenMinutes
    },
    
    // 获取缓存数据
    getCacheData(cacheKey) {
      const cacheData = uni.getStorageSync(cacheKey)
      return cacheData ? cacheData.data : null
    },
    
    // 设置缓存数据
    setCacheData(cacheKey, data) {
      const cacheData = {
        data: data,
        timestamp: Date.now()
      }
      uni.setStorageSync(cacheKey, cacheData)
    },
    
    // 加载商品分类
    async loadCategories() {
      // 检查缓存是否有效
      const orgId = API_CONFIG.ORG_ID
      const cacheKey = `product_categories_tree_cache_${orgId}`
      if (this.isCacheValid(cacheKey)) {
        const cachedData = this.getCacheData(cacheKey)
        if (cachedData && cachedData.length > 0) {
          this.categories = cachedData
          return
        }
      }
      
      try {
        const response = await listMobileCategoryTree({
          status: '0' // 0表示正常状态
        })
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          // 为每个分类添加展开状态
          const processCategories = (categories) => {
            return categories.map(category => {
              const processedCategory = {
                ...category,
                expanded: false // 默认收起
              }
              if (category.children && category.children.length > 0) {
                processedCategory.children = processCategories(category.children)
              }
              return processedCategory
            })
          }
          
          this.categories = processCategories(response.rows)
          
          // 缓存分类数据
          this.setCacheData(cacheKey, this.categories)
        } else {
          this.categories = []
        }
      } catch (error) {
        console.error('获取商品分类数据失败:', error)
        this.$modal.showToast('获取分类数据失败')
        this.categories = []
      }
    },
    
    // 加载商品数据
    async loadProducts(isLoadMore = false) {
      if (this.isLoading) return
      
      this.isLoading = true
      
      try {
        const currentPageNum = isLoadMore ? this.currentPage + 1 : 1
        
        // 如果不是加载更多，重置数据
        if (!isLoadMore) {
          this.allProducts = []
          this.hasMore = true
          
          // 仅对"全部"分类尝试从缓存获取
          if (this.currentCategoryId === 'all') {
            const orgId = API_CONFIG.ORG_ID
            const cacheKey = `all_products_cache_${orgId}`
            if (this.isCacheValid(cacheKey)) {
              const cachedData = this.getCacheData(cacheKey)
              if (cachedData && cachedData.length > 0) {
                 this.allProducts = cachedData
                 this.currentPage = 1
                 // 修复：缓存数据通常是第一页的完整数据，如果数量等于pageSize说明可能还有更多
                 // 但如果小于pageSize，说明这就是全部数据了
                 this.hasMore = cachedData.length === this.pageSize
                 this.isLoading = false
                 return
               }
            }
          }
        }
        
        let response
        if (this.currentCategoryId === 'all') {
          // 获取所有商品
          response = await listMobileProduct({
            pageNum: currentPageNum,
            pageSize: this.pageSize
          })
        } else {
          // 根据分类获取商品
          response = await listMobileProductByCategory({
            categoryId: this.currentCategoryId,
            pageNum: currentPageNum,
            pageSize: this.pageSize
          })
        }
        
        if (response.code === 200 && response.rows) {
          
          // 将后端数据转换为前端需要的格式，过滤掉发布状态为0的商品
          const processedProducts = response.rows
            .filter(item => item.publishStatus !== 0) // 过滤掉发布状态为0的商品
            .map(item => {
              // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
              let imageUrl = item.mainImage || 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=400&h=400&fit=crop'
              
              return {
                id: item.productId,
                name: item.productName || '商品名称',
                description: item.detail || item.description || '暂无描述',
                price: item.price ? parseFloat(item.price) : 0,
                originalPrice: item.originalPrice ? parseFloat(item.originalPrice) : null,
                image: imageUrl,
                sales: item.saleCount || 0,
                isHot: item.isHot === '1',
                categoryId: item.categoryId
              }
            })
          
          if (isLoadMore) {
            // 加载更多：追加到现有数据，但需要去重
            const existingIds = new Set(this.allProducts.map(p => p.id))
            const newProducts = processedProducts.filter(p => !existingIds.has(p.id))
            
            // 如果没有新数据，不应该继续加载
            if (newProducts.length === 0) {
              this.hasMore = false
              return
            }
            
            this.allProducts = [...this.allProducts, ...newProducts]
            this.currentPage++
            
            // 检查是否还有更多数据：如果返回的数据量小于页面大小，说明没有更多数据了
            if (processedProducts.length < this.pageSize) {
              this.hasMore = false
            }
          } else {
            // 首次加载：替换数据
            this.allProducts = processedProducts
            this.currentPage = 1
            
            // 只对"全部"分类进行缓存，且只在第一页时缓存
            if (this.currentCategoryId === 'all' && currentPageNum === 1) {
              const orgId = API_CONFIG.ORG_ID
              this.setCacheData(`all_products_cache_${orgId}`, processedProducts)
            }
            
            // 检查是否还有更多数据
            this.hasMore = processedProducts.length >= this.pageSize
          }
        } else {
          if (!isLoadMore) {
            this.allProducts = []
          }
          this.hasMore = false
        }
      } catch (error) {
        console.error('获取商品数据失败:', error)
        this.$modal.showToast('获取商品数据失败')
        if (!isLoadMore) {
          this.allProducts = []
        }
        this.hasMore = false
      } finally {
        this.isLoading = false
      }
    },
    
    // 初始化主题色
    async initThemeColor() {
      try {
        // 优先从本地存储获取
        const localTheme = uni.getStorageSync('themeColor')
        if (localTheme) {
          this.themeColor = localTheme
        } else {
          // 从全局配置获取
          const globalTheme = await getThemeColorFromGlobal()
          this.themeColor = globalTheme || '1'
        }
        
        // 强制更新视图
        this.$forceUpdate()
      } catch (error) {
        console.error('初始化主题色失败:', error)
        this.themeColor = '1'
      }
    },
    
    // 将十六进制颜色转换为RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}` : '59, 130, 246'
    },
    
    // 调整颜色亮度
    lightenColor(color, amount) {
      const usePound = color[0] === '#'
      const col = usePound ? color.slice(1) : color
      const num = parseInt(col, 16)
      let r = (num >> 16) + amount * 255
      let g = (num >> 8 & 0x00FF) + amount * 255
      let b = (num & 0x0000FF) + amount * 255
      r = r > 255 ? 255 : r < 0 ? 0 : r
      g = g > 255 ? 255 : g < 0 ? 0 : g
      b = b > 255 ? 255 : b < 0 ? 0 : b
      return (usePound ? '#' : '') + (r << 16 | g << 8 | b).toString(16).padStart(6, '0')
    }
  }
}
</script>

<style lang="scss" scoped>
.shop-container {
  display: flex;
  height: 100vh;
  background: #f8fafc;
  position: relative;
  padding-bottom: 160rpx; /* 增加底部间距避免TabBar遮挡 */
}

/* 左侧分类导航 */
.category-sidebar {
  width: 200rpx;
  background: linear-gradient(180deg, #fff 0%, #f1f5f9 100%);
  position: fixed;
  left: 0;
  top: 0;
  height: 100vh;
  z-index: 10;
  
  .category-header {
    padding: 30rpx 20rpx 20rpx;
    
    .category-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #1e293b;
      text-align: center;
    }
  }
  
  .category-scroll {
    height: calc(100vh - 100rpx);
    
    .category-item {
      padding: 30rpx 20rpx;
      text-align: center;
      border-bottom: 1rpx solid #f1f5f9;
      transition: all 0.3s ease;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:active {
        transform: scale(0.95);
      }
      
      &.active {
        font-weight: 600;
      }
      
      &.parent-category {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .category-content {
          flex: 1;
          padding: 20rpx 0;
        }
        
        .expand-icon {
          padding: 10rpx 6rpx;
          font-size: 16rpx;
          color: #999;
          min-width: 26rpx;
          text-align: center;
        }
      }
      
      &.child-category {
        padding-left: 40rpx;
        font-size: 28rpx;
        color: #666;
        background: rgba(248, 250, 252, 0.8);
        
        &.active {
          font-weight: 600;
        }
        
        .category-text {
          font-size: 24rpx;
          color: #64748b;
        }
      }
      
      .category-text {
        font-size: 26rpx;
        color: #475569;
        transition: all 0.3s ease;
        flex: 1;
      }
    }
    
    .child-categories {
      background-color: #f8f8f8;
    }
  }
}

/* 右侧商品内容 */
.product-content {
  flex: 1;
  margin-left: 200rpx;
  
  .product-scroll {
    height: 100%;
    
    .product-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20rpx;
      padding: 20rpx;
      
      .product-card {
        width: 100%;
        max-width: 340rpx;
        background: #fff;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
        border: 1rpx solid #e2e8f0;
        overflow: hidden;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        
        &:active {
          transform: scale(0.98);
          box-shadow: 0 8rpx 30rpx rgba(var(--theme-primary-rgb), 0.12);
        }
        
        .product-image-container {
          position: relative;
          width: 100%;
          height: 200rpx;
          overflow: hidden;
          border-radius: 16rpx 16rpx 0 0;
          
          .product-image {
            width: 100%;
            height: 100%;
            border-radius: 16rpx 16rpx 0 0;
            transition: transform 0.3s ease;
            object-fit: cover;
            display: block;
          }
          
          .product-badge {
            position: absolute;
            top: 12rpx;
            left: 12rpx;
            padding: 8rpx 16rpx;
            border-radius: 20rpx;
            
            .badge-text {
              font-size: 20rpx;
              color: #fff;
              font-weight: 600;
            }
          }
        }
        
        &:active .product-image {
          transform: scale(1.05);
        }
        
        .product-info {
          padding: 15rpx;
          
          .product-name {
            font-size: 26rpx;
            color: #1e293b;
            font-weight: 600;
            margin-bottom: 6rpx;
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          

          
          .product-price-row {
            display: flex;
            align-items: center;
            margin-bottom: 12rpx;
            
            .product-price {
              font-size: 28rpx;
              font-weight: bold;
              margin-right: 12rpx;
            }
            
            .product-original-price {
              font-size: 22rpx;
              color: #94a3b8;
              text-decoration: line-through;
            }
          }
          
          .product-bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .product-sales {
              font-size: 20rpx;
              color: #64748b;
            }

          }
        }
      }
    }
    
    /* 空状态提示 */
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 120rpx 40rpx;
      
      .empty-image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 40rpx;
        opacity: 0.6;
      }
      
      .empty-text {
        font-size: 32rpx;
        color: #64748b;
        margin-bottom: 16rpx;
        font-weight: 500;
      }
      
      .empty-desc {
        font-size: 26rpx;
        color: #94a3b8;
      }
    }
    
    /* 加载状态提示 */
    .loading-more {
      padding: 30rpx;
      text-align: center;
      
      .loading-text {
        font-size: 26rpx;
      }
    }
    
    .no-more {
      padding: 30rpx;
      text-align: center;
      
      .no-more-text {
        font-size: 26rpx;
      }
    }
  }
  
  /* TabBar安全区域 */
  .tabbar-safe-area {
    height: 200rpx;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }
}


</style>